<template>
    <view class="layout">
        <view class="topRow">
            <view class="wordBank">
                {{ storeName || "未选择词库" }}
            </view>
            <view class="selectBtn" @click="onClickSelect">
                选择词库
            </view>

        </view>
        <view class="progressCircle">

            <view class="persent">
                {{completionRate}}%
            </view>
            <view class="title">
                完成度
            </view>
        </view>
        <view class="startBtn" @click="onStartStudy">开始识记</view>

        <uni-popup ref="selectDialog" type="center" :is-mask-click="false">
            <view class="selectDialog">
                <view class="dialogContent">
                    <view class="dialogTitle">
                        请选择词库
                    </view>
                    <scroll-view scroll-y="true" class="scrollView">
                        <view v-for="item in wordBandMapList" :key="item.wordBankId">
                            <view :class="[item.wordBankId == tempSelectedId ? 'active-item' : 'item']"
                                @click="onClickItem(item.wordBankId)">
                                {{item.title}}
                            </view>
                        </view>
                    </scroll-view>
                    <view class="btnRow">
                        <view class="btnLeft" @click="onConfirm">
                            确认
                        </view>
                        <view class="btnRight" @click="onCloseDialog">
                            取消
                        </view>
                    </view>
                </view>
                <uni-icons type="clear" size="100rpx" @click="onCloseDialog"></uni-icons>
            </view>
        </uni-popup>


        <!-- <button size="mini" @click="wxLogin()">微信登录页面</button> -->
        <!-- <button size="mini" @click="gotoUniCloudCRUDPage()">前往云函数crud页面</button> -->
    </view>
</template>

<script setup>
    import {
        ref,
        computed
    } from "vue";
	import { onLoad, onShow, onReady, onUnload } from '@dcloudio/uni-app';
	
	import * as XLSX from 'xlsx';
	
	import { useUserInfoStore } from '../../../store';
	import { useStudyInfoStore } from '../../../store';
	
	//获得store实例对象
	const userInfoStore = useUserInfoStore()
	const studyInfoStore = useStudyInfoStore()
	
    let selectedId = ref(undefined);
    let tempSelectedId = ref(undefined);
	
	let completionRate = ref(0);
	
	// {wordBankId: "GaoKao3500", title:"高考3500个英语单词表", url: "https://mp-aa7ff953-57bf-4040-820d-fe7d9bb8d181.cdn.bspapp.com/cloudstorage/e9aaea17-a26d-49cf-8760-54e3d18ee374.xls"},
	// {wordBankId: "GaoKao3500-1", title:"高考3500个英语单词表-1", url: "https://mp-aa7ff953-57bf-4040-820d-fe7d9bb8d181.cdn.bspapp.com/cloudstorage/6a49df06-fa6b-4411-8d8d-d835d74c9497.xls"},
	const wordBandMapList = ref([])
	
	onLoad(async () => {
	  console.log('进度页面加载');
	  
	  userInfoStore.clearSelectedStudentInfo();
	  
	  uni.showLoading({
		title: "正在配置词库",
	  	mask: true
	  })
	  const res = await uniCloud.callFunction({
	  	name: "getWordBanks",
	  })
	  wordBandMapList.value = res.result.data
	  
	  if(wordBandMapList.value.length === 0){
		  uni.hideLoading();
		  return;
	  }
	  
	  studyInfoStore.setAllWordBankInfo(wordBandMapList.value);
	  
	  console.log("阿斯顿撒旦")
	  console.log(wordBandMapList.value.length === 0)
	  // uniCloud.callFunction({
	  // 	name: "getWordBanks",
	  // }).then(res => {
	  // 	listArr.value = res.result.data
	  // })
	  
	  await downloadWordsBank()
	  // console.log("预期下载后");
	  // ///在此取到正在学习的词库id
	  // if(userInfoStore.userInfo.role === 0){
		 //  selectedId.value = userInfoStore.userInfo.currentStudyWordBankId
		 //  studyInfoStore.setWordBankId(userInfoStore.userInfo.currentStudyWordBankId)
	  // }
	  
	  // await refreshCount()
	  
	  // uni.hideLoading()
	})
	
	onReady(() => {
		if(userInfoStore.userInfo.role === 1){
			uni.$on('changeStudent',async ()=>{
				selectedId.value = userInfoStore.selectedStudentInfo.currentStudyWordBankId
				await refreshCount()
			})
		}

	})
	
	onUnload(()=>{
		// if(userInfoStore.userInfo.role === 1){
			uni.$off('changeStudent'); 
		// }
	})
	
	async function refreshCount() {
		console.log("进度啊啊啊啊")
		
		if(userInfoStore.userInfo.role === 2) {
			completionRate.value = 0
			return;
		}
		
		let res = undefined;
		
		/// mark01
		if(userInfoStore.userInfo.role === 0) {
			res = await uniCloud.callFunction({
				name: "countWords",
				data: {
					relateUuid: userInfoStore.userInfo.uuid,
					wordBankId: studyInfoStore.wordBankId
				}
			})
		} else if(userInfoStore.userInfo.role === 1){
			res = await uniCloud.callFunction({
				name: "countWords",
				data: {
					relateUuid: userInfoStore.selectedStudentInfo.uuid,
					wordBankId: studyInfoStore.wordBankId
				}
			})
		}
		
		if(res.result.code === 500){
			completionRate.value = 0
			return;
		}

		// let arr = (await uni.getStorage({
				 //  key: "GaoKao3500"
		// })).data;
		
		// let arr = uni.getStorageSync("GaoKao350012");
		// completionRate.value = ((res.result.data.num6 + res.result.data.known) / arr.length).toFixed(2)
		
		// if(studyInfoStore.wordBankId === undefined){
		if(selectedId.value === undefined){
			completionRate.value = 0
		} else {
			// console.log("侮辱")
			let arr = uni.getStorageSync(studyInfoStore.wordBankId);
			completionRate.value = (((res.result.data.num6 + res.result.data.known) / arr.length) * 100).toFixed(2)
		}
	}
	
	onShow(async () => {
		// let arr = uni.getStorageSync("1233");
		// console.log(arr)
		// if(arr === "" && selectedId.value != undefined) {
		// 	await refreshCount()
		// }
		await refreshCount()
		
	})

    function wxLogin() {
        uni.navigateTo({
            url: "/pages/login/login"
        })
    }

    function gotoUniCloudCRUDPage() {
        uni.navigateTo({
            url: "/pages/uni-cloud-study/uni-cloud-study"
        })
    }

    //词库名称
    const storeName = computed(() => {
        if (wordBandMapList.value.some(item => item.wordBankId == selectedId.value)) {
            return wordBandMapList.value.find(item => item.wordBankId == selectedId.value).title;
        }
        return "";
    })

    const selectDialog = ref(null);


    function onClickSelect() {
		// if(userInfoStore.userInfo.currentStudyWordBankId === undefined){
		// 	console.log(1)
		// }else {
		// 	console.log(2)
		// }
		if(userInfoStore.userInfo.role === 0){
			tempSelectedId.value = selectedId.value;
			selectDialog.value.open();
		} else if(userInfoStore.userInfo.role === 1){
			if(userInfoStore.selectedStudentInfo.uuid != ""){
				tempSelectedId.value = selectedId.value;
				selectDialog.value.open();
			} else {
				uni.showToast({
					title: "未选择学生",
					icon:"error"
				})
			}

		}


    }

    async function onConfirm() {
        if(tempSelectedId.value === undefined) {
			return;
		}
		uni,uni.showLoading({
			title: '正在加载',
			mask: true
		});
		/// mark01
		if(userInfoStore.userInfo.role === 0) {
			const res = await uniCloud.callFunction({
			  name: 'selectMemorization',
			  data: {
				relateUuid: userInfoStore.userInfo.uuid,
				wordBankId: tempSelectedId.value
			  }
			})
			if (res.result.code === 200) {
				selectedId.value = tempSelectedId.value;
				studyInfoStore.setWordBankId(selectedId.value);
				
				await uniCloud.callFunction({
				  name: 'updateStudyWordBankId',
				  data: {
					uuid: userInfoStore.userInfo.uuid,
					currentStudyWordBankId: selectedId.value
				  }
				})
			}

		} else if(userInfoStore.userInfo.role === 1) {
			const res = await uniCloud.callFunction({
			  name: 'selectMemorization',
			  data: {
				relateUuid: userInfoStore.selectedStudentInfo.uuid,
				wordBankId: tempSelectedId.value
			  }
			})
			if (res.result.code === 200) {
				selectedId.value = tempSelectedId.value;
				studyInfoStore.setWordBankId(selectedId.value);
				
				await uniCloud.callFunction({
				  name: 'updateStudyWordBankId',
				  data: {
					uuid: userInfoStore.selectedStudentInfo.uuid,
					currentStudyWordBankId: selectedId.value
				  }
				})
			}
		}

		// if (res.result.code === 200) {
		// 	selectedId.value = tempSelectedId.value;
		// 	studyInfoStore.setWordBankId(selectedId.value);
		// }
		selectDialog.value.close();
		uni.hideLoading()
		await refreshCount()
		// console.log(res)
        
    }

    function onCloseDialog() {
        selectDialog.value.close();
    }

	
    function onStartStudy() {
		if(selectedId.value === undefined){
			uni.showToast({
				title: "未选择词库",
				icon:"error"
			})
			return;
		}
		if(!storeName.value) {
			uni.showModal({
				title: '提示',//标题
				content: '该词库已被移除，请重新选择词库。',//提示内容
				showCancel: false//不显示取消按钮
			  })
			return
		}
        uni.navigateTo({
            url: "/pages/index/index"
        })
    }

    function onClickItem(id) {
        tempSelectedId.value = id;
    }
	
	async function downloadWordsBank() {
		// parseExcel(`${wx.env.USER_DATA_PATH}/${GaoKao3500}.xls`)
		
		wordBandMapList.value.map(async item => 
			//判断是否存在文件
			await uni.getFileSystemManager().access({
				path: `${wx.env.USER_DATA_PATH}/${item.wordBankId}.xls`,
				success: async (res) => {
					console.log(res)
					if(uni.getStorageSync(item.wordBankId) === ""){
						parseExcel(`${wx.env.USER_DATA_PATH}/${item.wordBankId}.xls`, item.wordBankId)
					}
					///在此取到正在学习的词库id
					if(userInfoStore.userInfo.role === 0){
					    selectedId.value = userInfoStore.userInfo.currentStudyWordBankId
					    studyInfoStore.setWordBankId(userInfoStore.userInfo.currentStudyWordBankId)
					}
					
					await refreshCount()
					
					uni.hideLoading()
				},
				fail: async (res) => {
					await uni.downloadFile({
						// url: `https://mp-aa7ff953-57bf-4040-820d-fe7d9bb8d181.cdn.bspapp.com/${item.wordBankId}.xls`,
						url: item.url,
						success: async (res) => {
							if (res.statusCode === 200) {
								console.log('文件下载成功:', res.tempFilePath);
								
								// 2. 保存文件到本地
								await uni.saveFile({
									tempFilePath: res.tempFilePath, // 下载的临时文件路径
									filePath: `${wx.env.USER_DATA_PATH}/${item.wordBankId}.xls`, // 保存到本地的路径和文件名
									success: async (saveResult) => {
										console.log('文件保存成功:', saveResult.savedFilePath);
										// parseExcel(saveResult.savedFilePath)
										parseExcel(`${wx.env.USER_DATA_PATH}/${item.wordBankId}.xls`, item.wordBankId)
										// resolve(saveResult.savedFilePath); // 返回保存的文件路径
										console.log("解析之后");
										
										///在此取到正在学习的词库id
										if(userInfoStore.userInfo.role === 0){
										    selectedId.value = userInfoStore.userInfo.currentStudyWordBankId
										    studyInfoStore.setWordBankId(userInfoStore.userInfo.currentStudyWordBankId)
										}
										
										await refreshCount()
										
										uni.hideLoading()
									},
									fail: (saveError) => {
										console.error('文件保存失败:', saveError);
										reject(saveError);
									}
								});
							} else {
								console.error('文件下载失败:', res);
								// reject(new Error('文件下载失败'));
							}
						}
					});
				},
			})
		)
		

	}
	
	// 解析 Excel 文件
	function parseExcel(filePath, wordBankId) {
	   //  await uni.getFileSystemManager().readFile({
	   //      filePath: filePath,
	   //      encoding: 'binary',
	   //      success:async (res) => {
				// const workbook = XLSX.read(res.data, { type: 'binary' });
	   //          // 获取第一个工作表
	   //          const sheetName = workbook.SheetNames[0];
	   //          const sheet = workbook.Sheets[sheetName];
	   //          // 将工作表转换为 JSON 数据
	   //          const jsonData = XLSX.utils.sheet_to_json(sheet, {header: 2});
				// uni.setStorageSync(wordBankId, jsonData);
				// // await uni.setStorage({
				// // 	key: wordBankId,
				// // 	data: jsonData
				// // })
	   //          console.log(jsonData); // 打印解析后的数据
	   //      },
	   //      fail: (err) => {
	   //          console.error('文件读取失败', err);
	   //      }
	   //  });
		
		const res = uni.getFileSystemManager().readFileSync(
			filePath,
			'binary'
		)
		const workbook = XLSX.read(res, { type: 'binary' });
		// 获取第一个工作表
		const sheetName = workbook.SheetNames[0];
		const sheet = workbook.Sheets[sheetName];
		// 将工作表转换为 JSON 数据
		const jsonData = XLSX.utils.sheet_to_json(sheet, {header: 2});
		uni.setStorageSync(wordBankId, jsonData);
		console.log(jsonData); // 打印解析后的数据
		
	}
</script>

<style lang="scss" scoped>
    .layout {
        display: flex;
        flex-direction: column;
        align-items: center;

        .topRow {
            display: flex;
            flex-direction: column;
            align-items: center;

            // justify-content: space-between;
            // width: 100%;
            .wordBank {
                font-size: 30px;
                margin: 30rpx 0;
            }

            .selectBtn {
                padding: 20rpx 70rpx;
                background-color: orange;
                border-radius: 50rpx;
                font-size: 16px;
                color: white;
                display: flex;
                justify-content: center;
                font-size: 20px;
            }
        }

        .progressCircle {
            margin-top: 50rpx;
            width: 300rpx;
            height: 300rpx;
            background-color: #F6465D;
            border-radius: 50%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;

            .persent {
                color: white;
                font-size: 30px;
            }

            .title {
                font-size: 18px;
            }
        }

        .startBtn {
            margin-top: 50rpx;
            padding: 20rpx 80rpx;
            background-color: #18BB7C;
            border-radius: 50rpx;
            font-size: 20px;
            color: white;
        }

        .selectDialog {
            display: flex;
            flex-direction: column;
			align-items: center;
            gap: 60rpx;

            .dialogContent {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 40rpx;
                background-color: white;
                border-radius: 50rpx;
                width: 75vw;

                .dialogTitle {
                    margin-bottom: 80rpx;
                    padding: 15rpx 50rpx;
                    border-radius: 50rpx;
                    background-color: #18BB7C;
                    color: white;
                    font-size: 24px;
                }

                .scrollView {
                    max-height: 500rpx;

                    .item {
                        padding: 25rpx 15rpx;
                        margin-bottom: 20rpx;
                        border: 2rpx solid #EBEBEB;
                        font-size: 24px;
                        border-radius: 20rpx;
                    }

                    .active-item {
                        padding: 25rpx 15rpx;
                        margin-bottom: 20rpx;
                        border: 2rpx solid orange;
                        font-size: 24px;
                        border-radius: 20rpx;
                    }


                }

                text {
                    color: red;
                    font-size: 24px;
                }

                .btnRow {
                    display: flex;
                    flex-direction: row;
                    gap: 20rpx;
                    color: white;
                    font-size: 26px;
                    margin-top: 50rpx;

                    .btnLeft {
                        padding: 20rpx 50rpx;
                        background-color: #18BB7C;
                        border-radius: 50rpx;
                    }

                    .btnRight {
                        padding: 20rpx 50rpx;
                        background-color: orange;
                        border-radius: 50rpx;
                    }
                }
            }

        }
    }
</style>